<template>
  <div class="permission">
    <el-dialog
      :title="'为 ' + editClickNode.name + ' 分配权限'"
      :visible="showEditPerm"
      @close="cancelClick"
    >
      <el-tree
        :data="data"
        show-checkbox
        check-strictly
        default-expand-all
        node-key="id"
        :default-checked-keys="defaultCheck"
        ref="tree"
        highlight-current
        :props="defaultProps"
      >
      </el-tree>
      <el-row type="flex" justify="center" style="margin-top:40px">
        <el-button type="primary" @click="primaryClick">确认</el-button>
        <el-button @click="cancelClick">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionsList } from '@/api/permission'
import { assignPrem, getRoleById } from '@/api/setting'
import { toTree } from '@/utils'
export default {
  name: 'permission',
  data () {
    return {
      data: [],
      defaultCheck: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  props: {
    showEditPerm: {
      type: Boolean,
      default: false
    },
    editClickNode: {
      type: Object,
      default: {}
    }
  },
  methods: {
    //   获取数据
    async getPermissionsList () {
      let res = await getPermissionsList()
      // 处理成树状结构
      this.data = toTree(res.data, 0)
    },
    // 获取选中的角色的权限
    getRoleById () {
      // 这里又必须用到这个美妙的nextTick()
      this.$nextTick(async () => {
        let res = await getRoleById(this.editClickNode.id)
        this.defaultCheck = res.data.permIds
      })
    },
    // 关闭事件
    cancelClick () {
      this.$emit('update:showEditPerm', false)
    },
    // 确认按钮
    async primaryClick () {
      let ids = await this.$refs.tree.getCheckedKeys()

      await assignPrem({ id: this.editClickNode.id, permIds: ids })
      this.$message.success('给' + this.editClickNode.name + '权限分配成功')
      this.$emit('update:showEditPerm', false)
    }
  },
  created () {
    this.getPermissionsList()
  }
}
</script>

<style></style>
